package top.wjgyy.tools.ddns.config;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.commons.compress.utils.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.charset.StandardCharsets;

public class ConfigReder {

    public static <T> T getConfig(String fileName, Class<T> clazz) {
        fileName = fileName.startsWith("/") ? fileName.substring(1) : fileName.startsWith("\\") ? fileName.substring(1) : fileName;
        File file = new File("config/" + fileName);
        if (!file.exists()) {
            try {
                new File("config/").mkdirs();
                file.createNewFile();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        T model = null;
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            String str = new String(IOUtils.toByteArray(fis), "UTF-8");
            T modelNew = JSON.parseObject(str, clazz);
            model = str != null && !"".equals(str) ? modelNew : clazz.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) fis.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return model;
    }

    public static void saveConfig(String fileName, Object config) {
        fileName = fileName.startsWith("/") ? fileName.substring(1) : fileName.startsWith("\\") ? fileName.substring(1) : fileName;
        File file = new File("config/" + fileName);

        try {
            if (!file.exists()) {
                String path = file.getAbsolutePath();
                new File(path.substring(0, path.lastIndexOf("\\"))).mkdirs();
                file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file, false);
            JSONObject object = JSON.parseObject(JSON.toJSONString(config, SerializerFeature.PrettyFormat));
            if (object.containsKey("observableModels")) object.remove("observableModels");
            fos.write(JSON.toJSONString(object, SerializerFeature.PrettyFormat).getBytes(StandardCharsets.UTF_8));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) fos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
